#https://beer.sandbox.crptech.ru/
#https://markirovka.crpt.ru/ markirovka.crpt.ru
#https://habr.com/ru/articles/721622/
#https://markirovka.crpt.ru

import base64
import win32com.client
import os
import sys
import json
import datetime
import time
import jwt


CADES_BES = 1
CADES_DEFAULT = 0
CAPICOM_ENCODE_BASE64 = 0
CAPICOM_CURRENT_USER_STORE = 2
CAPICOM_MY_STORE = 'My'
CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2

SECRET_KEY = ''

# 3
oStore = win32com.client.Dispatch("CAdESCOM.Store")
oStore.Open(CAPICOM_CURRENT_USER_STORE, CAPICOM_MY_STORE, CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED)
for val in oStore.Certificates:
    #print(val.SerialNumber )
    if val.SerialNumber == "019606DD00C5AFD1B74D3BDB07DA28919F":
        oCert = val
oStore.Close


#4
oSigner = win32com.client.Dispatch("CAdESCOM.CPSigner")
oSigner.Certificate = oCert
oSigningTimeAttr = win32com.client.Dispatch("CAdESCOM.CPAttribute")
oSigningTimeAttr.Name = 0
oSigningTimeAttr.Value = datetime.datetime.now()
oSigner.AuthenticatedAttributes2.Add(oSigningTimeAttr)

win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')

xml_file = sys.argv[1]
pg = sys.argv[2]

with open(xml_file, 'rb') as f:
    document_base64=base64.b64encode(f.read())
    document_base64=document_base64.decode('ascii')
    #print(document_base64)


try:
    with open('jwt.cfg','r') as f:
        token=f.read()
        jwt.decode(token,SECRET_KEY,algorithms=["HS256"],options=dict(verify_signature=False,verify_exp=True))

except Exception as E:

    #5

    url = "https://markirovka.crpt.ru/api/v3/true-api/auth/key" 
    params = {}
    #win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
    win_http.Open("GET", url, False)
    win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
    win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
    win_http.Send(json.dumps(params))
    win_http.WaitForResponse()
    items  = json.loads(win_http.ResponseText)
    CodeAuth = items['data']

                                       
    #6
                                       
    oSignedData = win32com.client.Dispatch("CAdESCOM.CadesSignedData")
    oSignedData.ContentEncoding = 1
    message = CodeAuth
    message_bytes = message.encode('ascii')
    base64_bytes = base64.b64encode(message_bytes)
    base64_message = base64_bytes.decode('ascii')
    oSignedData.Content = base64_message
    sSignedData = oSignedData.SignCades(oSigner, CADES_BES, False, CAPICOM_ENCODE_BASE64)

    #7
    url = "https://markirovka.crpt.ru/api/v3/true-api/auth/simpleSignIn"

    paramskey ={
      'uuid': items['uuid'],
      'data': sSignedData
    }

    win_http.Open("POST", url, False)
    win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
    win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
    win_http.Send(json.dumps(paramskey))
    win_http.WaitForResponse()
    token =json.loads(win_http.ResponseText)["token"]
    with open('jwt.cfg','w+') as f:
        f.write(token)


#-----------------------------------------------
                                   
oSignedData = win32com.client.Dispatch("CAdESCOM.CadesSignedData")
oSignedData.ContentEncoding = 1
oSignedData.Content = document_base64
sSignedData = oSignedData.SignCades(oSigner, CADES_BES, True, CAPICOM_ENCODE_BASE64)

#7
url = "https://markirovka.crpt.ru/api/v3/true-api/lk/documents/create?pg="+pg

paramskey ={
            'type' : 'AGGREGATION_DOCUMENT_XML',
            'document_format' : 'XML',
            'product_document' : document_base64,
            'signature': sSignedData.replace('\r\n','') }

win_http.Open("POST", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("Authorization","Bearer "+token)
win_http.Send(json.dumps(paramskey))
win_http.WaitForResponse()
print(xml_file+"    "+(uuidDoc := win_http.ResponseText), end="")


#8




url = "https://markirovka.crpt.ru/api/v4/true-api/doc/list?number="+uuidDoc+"&pg="+pg

params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("Authorization",str("Bearer "+token))
#time.sleep(1)

status = 'IN_PROGRESS'
while status == 'IN_PROGRESS':
    win_http.Send(json.dumps(params))
    win_http.WaitForResponse()
    try:
        status = json.loads(win_http.ResponseText)["results"][0]["status"]
    except:
        status = 'IN_PROGRESS'
    time.sleep(5)

print("    "+status)

#"status":"ACCEPTED"
